public class InviteListController {

    private Opportunity oppty;
    private List<PersonWrapper> invitees;

    private LotusLiveConfig__c config {
    	get { 
    		if (config == null) {
    			config = [Select Id, Name, Protocol__c, LotusLiveServer__c, CompanyKey__c From LotusLiveConfig__c Limit 1];
    		}
    		return config;
    	}
    	set {}
    }
    private String username {
    	get { 
    		if (username == null) {
    			LotusLiveUser__c u = [Select Name, Password__c From LotusLiveUser__c Where User__c = :UserInfo.getUserId() Limit 1];
    			username = u.Name;
    			if (password == null) password = u.Password__c;
    		}
    		return username;
    	} 
    	set {}
    }
    private String password {
    	get {
    		if (password == null) {
    			LotusLiveUser__c u = [Select Name, Password__c From LotusLiveUser__c Where User__c = :UserInfo.getUserId() Limit 1];
    			password = u.Password__c;
    			if (username == null) username = u.Name;
    		}
    		return password;
    	}
    	set {}
    } 
    private String activitiesServer = config.LotusLiveServer__c; 
    private String protocol = config.Protocol__c; 

    public Task myTask { get; set; }
    public String activityId;
    public String scriptToRun { get; set; }


    public String mySubject { 
        get {
            if (mySubject == null) {
                mySubject = '';
            }
            return mySubject;
        }
        set; 
    }
    public String meetingStarted { 
        get {
            if (meetingStarted == null) {
                meetingStarted = 'true';
            } else {
                meetingStarted = 'false';
            }
            return meetingStarted;
        } 
        set; 
    }
    
    private String meetingId = '007-339';
    
    public String getMeetingParams() {
        String out = '?id=' + meetingId + '&extSF=1';
        if (invitees != null) {
            out += '&extSFInvite=';
            for (PersonWrapper pw : invitees) {
                out += pw.Email + ',';
            }
            out = out.substring(0, out.length() - 1);
        }
        out += '&extSFMail=fdc-bh@5wfgf16tpkenfbf1mf45u3vcu.in.salesforce.com';
        out += '&extSFOpportunityId=' + oppty.Id;
        System.debug(LoggingLevel.INFO, '\n\nGETTING PARAMS - ACTIVITY ID IS: ' + activityId + '\n\n');
        if (activityId != null) {
            out += '&extSFActivityId=' + activityId;
        }
        return out;
    }
    
    public PageReference saveInviteList() {
        invitees = new List<PersonWrapper>();
        for (PersonWrapper pw : acctContacts) {
            if (pw.invite) {
                invitees.add(pw);
            }
            System.debug(LoggingLevel.INFO, '\n\n' + pw.Name + ' ' + pw.invite + '\n');
        }
        for (PersonWrapper pw : shareUsers) {
            if (pw.invite) {
                invitees.add(pw);
            }
        }
        for (PersonWrapper pw : opptyContactRoles) {
            if (pw.invite) {
                invitees.add(pw);
            }
        }
        for (PersonWrapper pw : accountTeam) {
            if (pw.invite) {
                invitees.add(pw);
            }
        }
        for (OpptyPartnerWrapper opw : partnerAccounts) {
            for (PersonWrapper pw : opw.contacts) {
                if (pw.invite) {
                    invitees.add(pw);
                }
            }
        }
        System.debug('Dude, where\'s my car?');
        return null;
    }

    public PageReference updateOppty() {
        myTask.Subject = 'BH Meeting - ' + mySubject;
        myTask.Status = 'In Progress';
        myTask.ActivityTitle__c = mySubject;
        myTask.ActivityDate = Date.today();
        myTask.WhatId = oppty.Id;
        myTask.Description = 'Created on-line meeting with: \n';
        for (PersonWrapper pw : invitees) {
            myTask.Description += pw.Name + '\n';
        }
        System.debug(LoggingLevel.INFO, '\n\nAbout to create a new activity...');
        createMeetingActivity();
        if (activityId != null) {
            myTask.activityId__c = activityId;
        }
        
        myTask.LaunchUrl__c = getMeetingParams();
        
        System.debug(LoggingLevel.INFO, '\n\nReady to insert Task...');
        
        if (myTask.Id != null) {
            update myTask;
        } else {
            insert myTask;
        }
        System.debug(LoggingLevel.INFO, '\n\nAll DB Actions are complete...');
        meetingStarted = 'true';
        scriptToRun = 'window.open("https://bluehouseisv.lotus.com/meetings/host' + getMeetingParams() + '", "Oppty Meeting");' +
                   'window.location = "";';
        
        return null;
    }
    
    private void createMeetingActivity() {
    
        String protocol = config.Protocol__c; 
        String username = username; 
        String password = password; 
        String activitiesServer = config.LotusLiveServer__c;
        String userId = config.CompanyKey__c;
        String activityTitle = 'testing123';
 
        AtomService activitiesService = new AtomService(protocol, activitiesServer, username, password);
        ActivitiesClient activitiesClient = new ActivitiesClient(activitiesService);

        ActivityEntry ae = new ActivityEntry();
        ae.addCategory('meetings');
        ae.addCategory('todos');
        ae.addCategory('salesforce');
        ae.setTitle('Track To Do Items from Meeting - ' + mySubject);
        Entry result = activitiesClient.createActivity(ae);
        //System.debug(LoggingLevel.INFO, '\n\nCreated activity is: ' + result.dump() + '\n');
        
        if (result != null) {
            activityId = result.extensions.get('activity').value;
            System.debug(LoggingLevel.INFO, '\n\nActivity Id is: ' + activityId + '\n\n');
        } else {
            activityId = null;
        }
    }
    
    public class OpptyPartnerWrapper {
        public String role { get; set; }
        public String name { get; set; }
        public List<PersonWrapper> contacts { get; set; }
        
        public OpptyPartnerWrapper(OpportunityPartner op) {
            role = op.Role;
            name = op.AccountTo.Name;
            contacts = new List<PersonWrapper>();
            List<Contact> opc = [Select Id, Email, Name, Title From Contact Where AccountId = :op.AccountToId];
            for (Contact c : opc) {
                contacts.add(new PersonWrapper(c));
            }
        }
    }
    public class PersonWrapper {
        public ID Id { get; set; }
        public String Name { get; set; }
        public String Email { get; set; }
        public Boolean invite { get; set; }
        public String title { get; set; }
        
        public PersonWrapper(User c) {
            this.Id = c.Id;
            this.Name = c.Name;
            this.Email = c.Division;
            this.invite = false;
            this.title = c.Title;
        }
        public PersonWrapper(Contact c) {
            this.Id = c.Id;
            this.Name = c.Name;
            this.Email = c.Email;
            this.invite = false;
            this.Title = c.Title;
        }
    }
    
    public List<PersonWrapper> acctContacts { 
        get { 
            if (acctContacts == null) { 
                acctContacts = new List<PersonWrapper>();
            } return acctContacts; 
        } 
        set; }
    public Boolean showAcctContacts { get; set; }
    
    public List<OpptyPartnerWrapper> partnerAccounts { get; set; }
    public boolean showPartners { get; set; }
    
    public List<PersonWrapper> opptyContactRoles { 
        get {
            if (opptyContactRoles == null) {
                opptyContactRoles = new List<PersonWrapper>();
            }
            return opptyContactRoles;
        }
        set; }
    public Boolean showOpptyContactRoles { get; set; }
    
    public List<PersonWrapper> shareUsers { 
        get {
            if (shareUsers == null) {
                shareUsers = new List<PersonWrapper>();
            }
            return shareUsers;
        }
        set; }
    public Boolean showShareUsers { get; set; }
    
    public List<PersonWrapper> accountTeam { 
        get {
            if (accountTeam == null) {
                accountTeam = new List<PersonWrapper>();
            }
            return accountTeam;
        }
        set; }
    public Boolean showAccountTeam { get; set; }
    
    public List<AccountShare> acctShares { get; set; }
    
    public InviteListController(ApexPages.StandardController controller) {
        oppty = (Opportunity)controller.getRecord();
        init(); 
    }
    /*public InviteListController() {
        oppty = [Select Id, AccountId, Name From Opportunity Where Id = :ApexPages.currentPage().getParameters().get('id')];
        init();
    }*/
    public void init() {
        partnerAccounts = new List<OpptyPartnerWrapper>();
        
        myTask = new Task();
        scriptToRun = '';
        showAccountTeam = showShareUsers = showOpptyContactRoles = showAcctContacts = false;
        Opportunity oppty = [Select Id, AccountId, Name From Opportunity Where Id = :ApexPages.currentPage().getParameters().get('id')];
        System.debug(LoggingLevel.INFO, '\n\nGetting person data...\n\n' + oppty);
        try {
            for (Contact c : [Select Id, Email, Name, Title From Contact Where AccountId = :oppty.AccountId]) {
                acctContacts.add(new PersonWrapper(c));
                showAcctContacts = true;
            }
            for (Contact c : [Select Id, Email, Name, Title From Contact Where Id in (Select ContactId From OpportunityContactRole Where OpportunityId = :oppty.Id)]) {
                opptyContactRoles.add(new PersonWrapper(c));
                showOpptyContactRoles = true;
            }
            acctShares = [Select UserOrGroupId From AccountShare Where AccountId = :oppty.AccountId];
            for (User u : [Select Id, Name, Email, Title, Division From User Where Id in (Select UserId From AccountTeamMember Where AccountId = :oppty.AccountId)]) {
                accountTeam.add(new PersonWrapper(u));
                showAccountTeam = true;
            }
            
            for (AccountShare share : acctShares) {
                if (String.valueOf(share.UserOrGroupId).startsWith('')) {
                    if (shareUsers == null) shareUsers = new List<PersonWrapper>();
                    shareUsers.add(new PersonWrapper([Select Id, Name, Email, Title, Division From User Where Id = :share.UserOrGroupId]));
                    showShareUsers = true;
                } else {
                    List<GroupMember> groupmembers = [Select UserOrGroupId From GroupMember Where Id = :share.UserOrGroupId];
                    for (GroupMember g : groupmembers) {
                        if (String.valueOf(g.UserOrGroupId).startsWith('')) {
                            if (shareUsers == null) shareUsers = new List<PersonWrapper>();
                            shareUsers.add(new PersonWrapper([Select Id, Name, Email, Title, Division From User Where Id = :g.UserOrGroupId]));
                            showShareUsers = true;
                        }
                    }
                }
            }
            loadPartnerAccounts();
            
        } catch (Exception e) {
        }
    }
    
    private void loadPartnerAccounts() {
        List<OpportunityPartner> pa = [Select Role, AccountTo.Name, AccountToId From OpportunityPartner Where OpportunityId = :oppty.Id and (Role != 'Client' and Role != 'Agent')];
        for (OpportunityPartner op : pa) {
            if (op.AccountToId != oppty.Id) {
                partnerAccounts.add(new OpptyPartnerWrapper(op));
                showPartners = true;
            }
        }
    }
    public String defaultText { 
        get { 
            if (defaultText == null) {
                defaultText = 'Hello!\n' +
                              'I\'d like to invite you to my meeting. Click this link to attend: https://bluehouse.lotus.com/meetings/join?id=908-046\n' +
                              '\n\nBest regards,\n' +
                              'Dave Carroll\n';
            }
            return defaultText;
        } 
        set; 
    }
}